/* Andreas Baum
 * IMClientApp.java
 * Handles the connection of an IM client to the IM server
 * CS 78 - Networks - Programming Assignment 1
 */


package ChatServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;



public class AdminClient {

	public static int SERVER_PORT = 4444;

	public static String ADMIN = "[admin]";
	private static Socket socket;
	private static PrintWriter out;
	private static BufferedReader in;
	private static String HOST = "localhost";

	public AdminClient() {
		out = null;
		in = null;
		socket = null;

		System.out.println("Establishing admin session...");

		try {
			// send connection request:
			socket = new Socket(HOST, SERVER_PORT);
			// establish in and out streams
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		} catch (UnknownHostException e) {
			// If host can't be found:
			System.err.println("ERROR: Don't know about host: " + HOST + ".");
			System.exit(1);
		} catch (IOException e) {
			// If host doesn't accept connections:
			System.err.println("ERROR: Couldn't get I/O for "
					+ "the connection to: " + HOST + ".");
			System.exit(1);
		}

		// Confirm connection:
		System.out.println("Admin session established.");

		// send username to the server
		out.println("USR " + ADMIN);

		try {
			// Receive handshake from server (either accepted username
			// or invalid username)
			String response = in.readLine();

			// username is ok
			if (response.toUpperCase().startsWith("PRINT"))
				System.out.println(response.substring(6));

			// username is already used
			else {
				System.out.println(response.substring(4));
				System.exit(1);
			}

			// connection is established, hand it over to a client thread.
			@SuppressWarnings("unused")
			AdminThread clientThread = new AdminThread(socket);


			out.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


//	------------------------------------------
//	Standard functions:

//	Returns the name of the client:
	public String getName() {
		return ADMIN;
	}

//	Returns the socket:
	public Socket getSocket() {
		return socket;
	}

	// Standard toString method:
	public String toString() {
		return ADMIN + "\t" + socket;
	}

}